//
//  TSCreateScheduleViewController.m
//  chart
//
//  Created by xu on 15/8/22.
//  Copyright (c) 2015年 xu. All rights reserved.
//

#import "TSCreateScheduleViewController.h"
#import "TSDatePickerTextField.h"
#import "TSToolBarTextField.h"
#import "TSPickerTextField.h"
#import "TSJournalModel.h"
#import "TSTools.h"
#import "TSMessageListCell.h"
#import "TSEditContentController.h"
#define SEARCH_LABEL_WIDTH  100.f
#define SEARCH_LABEL_HEIGHT 35.f
#define SEARCH_ROW_GAP 10.f

@interface TSCreateScheduleViewController ()<UITextViewDelegate>{
}
@end

@implementation TSCreateScheduleViewController{
    TSToolBarTextField *titleTextField;
    TSDatePickerTextField *startTimePickerTextField;
    TSDatePickerTextField *endTimePickerTextField;
    TSToolBarTextField *placeTextField;
    TSToolBarTextField *contentTextField;
    TSJournalItemModel *model;
    UIScrollView *scrollView;
}

@synthesize journalId,attachTextField;

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveContentViewController:) name:TSNotification_SaveContentController object:nil];
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentViewController:) name:TSNotification_PresentViewController object:nil];
    
    WS(weakSelf);
    if ([TSTools isEmpty:journalId]) {
        [self leftBarButtonWithTitle:nil barNorImage:[UIImage imageNamed:@"nav_dark_close"] barHltImage:nil action:^{
            if (!weakSelf) {
                return;
            }
            
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }];
        
        [self rightBarButtonWithTitle:@"创建" barNorImage:nil barHltImage:nil action:^{
            if (!weakSelf) {
                return;
            }
            
            [weakSelf onCreateBtnClick];
        }];
        
        self.navigationItem.title = @"创建个人日程";
    }
    else{
        if (self.isSelf) {
            [self rightBarButtonWithTitle:@"修改" barNorImage:nil barHltImage:nil action:^{
                if (!weakSelf) {
                    return;
                }
                
                [weakSelf onUpdateBtnClick];
            }];
        }
        else{
            [self rightBarButtonWithTitle:nil barNorImage:nil barHltImage:nil action:nil];
        }
        
        self.navigationItem.title = self.isSelf?@"修改个人日程":@"查看个人日程";
    }
    
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, currentDeviceWidth,currentDeviceHeight-NAV_AND_STATUS_BAR_HEIGHT)];
    scrollView.contentSize = CGRectMake(0, 0, currentDeviceWidth, currentDeviceHeight-NAV_AND_STATUS_BAR_HEIGHT+1).size;
    scrollView.scrollEnabled=YES;
    [self.view addSubview:scrollView];
    
    [self addTapGesture];
    
    [self addTitleRow];
    
    [self addTimeRow];
    
    [self addPlaceRow];
    
    [self addContentRow];
    
    [self addAttachRow];
    
//    [self addCompeleteBtn];
    
    model = [[TSJournalItemModel alloc] init];
    
    /* 如果是修改信息的话 */
    if (![TSTools isEmpty:journalId]) {
        [self getJournalInfoById];
    }
    [attachTextField setDelegate:self];
}

-(void)presentViewController:(NSNotification *)noti
{
    TSEditContentController *edit_vc = [[TSEditContentController alloc] init];
    TSBaseNavigationController *nav = [[TSBaseNavigationController alloc] initWithRootViewController:edit_vc];
    edit_vc.content = contentTextField.text;
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)getJournalInfoById
{
    WS(weakSelf);
    model.requestParams = @{TSDictionaryKeyDefine_Id:journalId};
    [model fetchWithPath:kRequestUrl_Journal_outOne_journal completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        [weakSelf setJournalInfoWithModel];
    } NoProgress:NO];
}

- (void)setJournalInfoWithModel
{
    if (model) {
        titleTextField.text = model.title;
        startTimePickerTextField.text = [TSTools getDateByTime:model.timeBegin];
        endTimePickerTextField.text = [TSTools getDateByTime:model.timeEnd];
        placeTextField.text = model.place;
        contentTextField.text = model.content;
        attachTextField.text = model.attachment;
    }
}

- (void)onCreateBtnClick
{
    WS(weakSelf);
    NSString *start_time = [NSString stringWithFormat:@"%f", startTimePickerTextField.datePicker.date.timeIntervalSince1970];
    NSString *end_time   = [NSString stringWithFormat:@"%f", endTimePickerTextField.datePicker.date.timeIntervalSince1970];
    model.requestParams  = @{TSDictionaryKeyDefine_Title:titleTextField.text?:@"", TSDictionaryKeyDefine_TimeBegin:start_time, TSDictionaryKeyDefine_TimeEnd:end_time, TSDictionaryKeyDefine_Place:placeTextField.text, TSDictionaryKeyDefine_Content:contentTextField.text};
    [model fetchWithPath:kRequestUrl_Journal_insert completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        if (isSucceeded) {
            [[LBToastManager manager] showtoast:@"创建成功"];
            
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:TSNotification_ScheduleCreateSucceeded object:nil];
        }
        else{
            [[LBToastManager manager] showtoast:@"创建失败, 请重试"];
        }
    } NoProgress:NO];
}

/* 更改个人日程 */
- (void)onUpdateBtnClick
{
    WS(weakSelf);
    NSString *start_time = [NSString stringWithFormat:@"%f", startTimePickerTextField.datePicker.date.timeIntervalSince1970];
    NSString *end_time   = [NSString stringWithFormat:@"%f", endTimePickerTextField.datePicker.date.timeIntervalSince1970];
    model.requestParams  = @{TSDictionaryKeyDefine_Id:journalId, TSDictionaryKeyDefine_Title:titleTextField.text?:@"", TSDictionaryKeyDefine_TimeBegin:start_time, TSDictionaryKeyDefine_TimeEnd:end_time, TSDictionaryKeyDefine_Place:placeTextField.text, TSDictionaryKeyDefine_Content:contentTextField.text};
    [model fetchWithPath:kRequestUrl_Journal_update completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        if (isSucceeded) {
            [[LBToastManager manager] showtoast:@"修改成功"];
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:TSNotification_ScheduleCreateSucceeded object:nil];
        }
        else{
            [[LBToastManager manager] showtoast:@"修改失败, 请重试"];
        }
        
    } NoProgress:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)addTapGesture
{
    /* 加入收键盘手势 */
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleField:)];
    [self.view addGestureRecognizer:tap];
}

/* 隐藏键盘 */
- (void)handleField:(UIGestureRecognizer*)gesture{
    for (UIView * view in self.view.subviews) {
        if ([view isFirstResponder]) {
            [view resignFirstResponder];
        }
    }
}

- (UILabel *)createLabel:(CGRect)frame Title:(NSString *)title
{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    [label setText:title];
    [label setFont:FONT(12.f)];
    
    return label;
}

- (void)addTitleRow
{
    UILabel *label = [self createLabel:CGRectMake(MARGIN_LEFT, MARGIN_TOP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"标题:"];
    [scrollView addSubview:label];
    
    titleTextField = [[TSToolBarTextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label.frame)+10.f, CGRectGetMinY(label.frame), currentDeviceWidth-MARGIN_LEFT*2-SEARCH_LABEL_WIDTH-10.f, SEARCH_LABEL_HEIGHT)];
    titleTextField.layer.borderWidth = 1.f;
    [scrollView addSubview:titleTextField];
}

- (void)addTimeRow
{
    UILabel *startL_label = [self createLabel:CGRectMake(MARGIN_LEFT, CGRectGetMaxY(titleTextField.frame)+SEARCH_ROW_GAP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"开始时间:"];
    [scrollView addSubview:startL_label];
    
    startTimePickerTextField = [[TSDatePickerTextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(startL_label.frame)+10.f, CGRectGetMinY(startL_label.frame), CGRectGetWidth(titleTextField.frame), SEARCH_LABEL_HEIGHT)];
    startTimePickerTextField.layer.borderWidth = 1.f;
    [scrollView addSubview:startTimePickerTextField];
    
    UILabel *end_label = [self createLabel:CGRectMake(MARGIN_LEFT, CGRectGetMaxY(startL_label.frame)+SEARCH_ROW_GAP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"结束时间:"];
    [scrollView addSubview:end_label];
    endTimePickerTextField = [[TSDatePickerTextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(end_label.frame)+10.f, CGRectGetMinY(end_label.frame), CGRectGetWidth(startTimePickerTextField.frame), SEARCH_LABEL_HEIGHT)];
    endTimePickerTextField.layer.borderWidth = 1.f;
    [scrollView addSubview:endTimePickerTextField];
}

- (void)addPlaceRow
{
    UILabel *label = [self createLabel:CGRectMake(MARGIN_LEFT, CGRectGetMaxY(endTimePickerTextField.frame)+SEARCH_ROW_GAP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"地点:"];
    [scrollView addSubview:label];
    
    placeTextField = [[TSToolBarTextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label.frame)+10.f, CGRectGetMinY(label.frame), CGRectGetWidth(startTimePickerTextField.frame), SEARCH_LABEL_HEIGHT)];
    placeTextField.layer.borderWidth = 1.f;
    [scrollView addSubview:placeTextField];
}

- (void)addContentRow
{
    UILabel *label = [self createLabel:CGRectMake(MARGIN_LEFT, CGRectGetMaxY(placeTextField.frame)+SEARCH_ROW_GAP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"内容:"];
    [scrollView addSubview:label];
    contentTextField = [[TSToolBarTextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label.frame)+10.f, CGRectGetMinY(label.frame), CGRectGetWidth(startTimePickerTextField.frame), 200)];
    contentTextField.layer.borderWidth = 1.f;
    [contentTextField setToolBarTextFieldType:3];
    [contentTextField setNotShowKeyboard:YES];
    [scrollView addSubview:contentTextField];
}
-(void)saveContentViewController:(NSNotification *)noti
{
    [contentTextField setText:noti.object];
}

- (void)addAttachRow
{
    UILabel *label = [self createLabel:CGRectMake(MARGIN_LEFT, CGRectGetMaxY(contentTextField.frame)+SEARCH_ROW_GAP, SEARCH_LABEL_WIDTH, SEARCH_LABEL_HEIGHT) Title:@"附件:"];
    [scrollView addSubview:label];
    
    attachTextField = [[TSToolBarTextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label.frame)+10.f, CGRectGetMinY(label.frame), CGRectGetWidth(startTimePickerTextField.frame), SEARCH_LABEL_HEIGHT)];
    attachTextField.layer.borderWidth = 1.f;
    attachTextField.delegate = self;
    [scrollView addSubview:attachTextField];
}

- (void)addCompeleteBtn
{
    UIButton *compelete_btn = [[UIButton alloc] initWithFrame:CGRectMake(MARGIN_LEFT, CGRectGetMaxY(attachTextField.frame)+SEARCH_ROW_GAP, currentDeviceWidth-2*MARGIN_LEFT, SEARCH_LABEL_HEIGHT)];
    compelete_btn.titleLabel.font = FONT(12);
    [compelete_btn setTitle:@"完成" forState:UIControlStateNormal];
    [compelete_btn setBackgroundColor:[UIColor grayColor]];
    [compelete_btn.layer setCornerRadius:5.f];
    [compelete_btn addTarget:self action:@selector(compeleteJournal:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:compelete_btn];
}

- (void)compeleteJournal:(UIButton *)sender
{
    WS(weakSelf);
    model.requestParams = @{TSDictionaryKeyDefine_Id:journalId?:@""};
    [model fetchWithPath:kRequestUrl_Journal_finish completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        if (isSucceeded) {
            [[LBToastManager manager] showtoast:@"修改成功"];
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:TSNotification_ScheduleCreateSucceeded object:nil];
        }
        else{
            [[LBToastManager manager] showtoast:@"修改失败, 请重试"];
        }
    } NoProgress:NO];
}



- (void)textViewDidBeginEditing:(UITextView *)textView{
    CGFloat textFieldFromTop =  textView.frame.origin.y;
    CGFloat offset = textFieldFromTop-currentDeviceHeight+NAV_AND_STATUS_BAR_HEIGHT +350;
    if(offset>0){
        [scrollView setContentOffset:CGPointMake(0, offset)];
    }
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    [scrollView setContentOffset:CGPointMake(0, 0)];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
